﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.DXErrorProvider;
using DevExpress.XtraGrid.Columns;
using JSales.ModuleSales;
using JsalesModel;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors.Repository;



namespace JSales.ModuleSales
{
    public partial class OrderForm : Form
    {
        public OrderForm()
        {
            InitializeComponent();
            InitValidationRules();
        }

        private string state = null;
        private string OrderID = null;
        private BindingSource orderBinding = new BindingSource();
        private BindingSource cusBinding = new BindingSource();
        private BindingSource userBinding = new BindingSource();
        private BindingSource levelBinding = new BindingSource();
        private BindingSource deptBinding = new BindingSource();
        private BindingSource productBinding = new BindingSource();

        private BindingList<TbOrderMX> orderMxs = new BindingList<TbOrderMX>();
        private BindingList<TbOrderMX> orderMxsImage = new BindingList<TbOrderMX>();

        private IList<TbOrderMX> OrderMxOld = new List<TbOrderMX>();

        private string GenExpression()
        {
            string expression = "AND CREATEBY=" + GlobalVar.cUser.UserID
                +"";
            return expression;
        }

        /// <summary>
        /// 初始化订单
        /// </summary>
        private void InitGrid()
        {
            using(JYEntities dbContext=new JYEntities())
            {
                //var orders = from i in dbContext.TbOrders
                //             from c in GlobalVar.GCustomers
                //             where i.CustomerID == c.CustomerID
                //             orderby i.CreateDate descending
                //             select new { i.CarryingAmount, i.Amount, i.CREATEBY, i.CreateDate, i.CustomerID, i.Cut, i.DeptID, i.IsApproval, i.IsCommit, i.IsDeleted, i.LastEditDate, i.ODesc, i.OrderID, i.CommitDate, i.ApprovalDate, c.Level };

                string sql = "SELECT o.CarryingAmount,o.Amount,o.CREATEBY,o.CreateDate,o.CustomerID,o.Cut,o.DeptID,o.IsApproval,o.IsCommit,o.IsDeleted,o.LastEditDate,o.ODesc,o.OrderID,o.CommitDate,o.ApprovalDate,c.Level  FROM dbo.tbOrder o LEFT JOIN dbo.tbCustomer c ON o.CustomerID = c.CustomerID WHERE 1=1"+GenExpression();
                IEnumerable<MyOrder> orders = dbContext.ExecuteQuery<MyOrder>(sql);
                if (orders.Any())
                {
                    orderBinding.DataSource = orders.OrderByDescending(o=>o.CreateDate); //订单
                }


                IQueryable<TbCustomer> customers = from i in GlobalVar.GCustomers
                                                   select i;
                if (customers.Any())
                {
                    cusBinding.DataSource = customers; //客户
                }

                IQueryable<TbUser> users = from i in GlobalVar.GUsers
                                           where i.IsDeleted == false
                                           select i;
                if (users.Any())
                {
                    userBinding.DataSource = users; //用户
                }

                IQueryable<TbCusLevel> levels = from i in GlobalVar.GCusLevels
                                                select i;
                if (levels.Any())
                {
                    levelBinding.DataSource = levels; //级别
                }

                IQueryable<TbDept> depts = from i in GlobalVar.GDepts
                                           where i.Isdeleted == false
                                           select i;
                if (depts.Any())
                {
                    deptBinding.DataSource = depts; //部门
                }

                IQueryable<TbProduct> products = from i in GlobalVar.GProductsAll
                                                 where i.IsDeleted == false
                                                 select i;
                if (products.Any())
                    productBinding.DataSource = products; //产品

                BindData();
            }
        }

        /// <summary>
        /// 订单表头初始化
        /// </summary>
        private void InitEditZone()
        {
            tbCarryingAmount.DataBindings.Clear();
            textEditTotalAmount.DataBindings.Clear();
            tbDesc.DataBindings.Clear();
            tbOrderID.DataBindings.Clear();
            LookupCustomer.DataBindings.Clear();
            LookupSale.DataBindings.Clear();
            lookUpDept.DataBindings.Clear();
            LookupLevel.DataBindings.Clear();
            dateApproval.DataBindings.Clear();
            dateCommit.DataBindings.Clear();
            dateCreate.DataBindings.Clear();
            checkEditCommit.DataBindings.Clear();
            checkEditApproval.DataBindings.Clear();
            checkEditCut.DataBindings.Clear();

            tbCarryingAmount.DataBindings.Add("Text", orderBinding, "CarryingAmount");
            textEditTotalAmount.DataBindings.Add("EditValue", orderBinding, "Amount");
            tbDesc.DataBindings.Add("Text", orderBinding, "ODesc");
            tbOrderID.DataBindings.Add("Text", orderBinding, "OrderID");
            LookupCustomer.DataBindings.Add("EditValue", orderBinding, "CustomerID");
            LookupSale.DataBindings.Add("EditValue", orderBinding, "CREATEBY");
            lookUpDept.DataBindings.Add("EditValue", orderBinding, "DeptID");
            LookupLevel.DataBindings.Add("EditValue", orderBinding, "Level");
            dateApproval.DataBindings.Add("Text", orderBinding, "ApprovalDate");
            dateCommit.DataBindings.Add("Text", orderBinding, "CommitDate");
            dateCreate.DataBindings.Add("Text", orderBinding, "CreateDate");
            checkEditCommit.DataBindings.Add("EditValue", orderBinding, "IsCommit");
            checkEditApproval.DataBindings.Add("EditValue", orderBinding, "IsApproval");
            checkEditCut.DataBindings.Add("EditValue", orderBinding, "Cut");
        }

        /// <summary>
        /// 数据绑定
        /// </summary>
        private void BindData()
        {
            gridControlOrder.DataSource = orderBinding; //订单
            LookupCustomer.Properties.DataSource = cusBinding; //客户
            LookupSale.Properties.DataSource = userBinding; //用户
            LookupLevel.Properties.DataSource = levelBinding; //级别
            lookUpDept.Properties.DataSource = deptBinding; //部门
            repositoryItemSearchLookUpEditProduct.DataSource = productBinding; //产品
            searchLookupEditProduct.Properties.DataSource = productBinding; //产品
            repositoryItemLookUpEditTypes.DataSource = GlobalVar.typeses;
        }

        private EditMode mode;
        private EditMode modeMX;

        private enum EditMode
        {
            Normal = 0,
            Edit = 1,
            Add = 2
        }

        /// <summary>
        /// 明细数据区初始化
        /// </summary>
        private void InitMx()
        {
            orderMxs.Clear();
            orderMxsImage.Clear(); ;
            var dbContext = new JYEntities();

            IQueryable<TbOrderMX> mxs = from i in dbContext.TbOrderMXes
                                        where i.OrderID == tbOrderID.Text
                                        select i;
            if (mxs.Any())
            {
                foreach (var x in mxs)
                {
                    orderMxs.Add(x);
                    orderMxsImage.Add(x);
                }
                BindMX();
            }
            else
            {
                orderMxs.Clear();
                orderMxsImage.Clear();
            }
        }

        /// <summary>
        /// 明细编辑区初始化
        /// </summary>
        private void InitMxEdit()
        {
            searchLookupEditProduct.DataBindings.Clear();
            textEditUnit.DataBindings.Clear();
            textEditQuant.DataBindings.Clear();
            calcEditPrice.DataBindings.Clear();
            textEditAmount.DataBindings.Clear();
            checkEditIsCut.DataBindings.Clear();

            searchLookupEditProduct.DataBindings.Add("EditValue", orderMxs, "ProductID");
            textEditUnit.DataBindings.Add("Text", orderMxs, "Unit");
            textEditQuant.DataBindings.Add("Text", orderMxs, "Quant");
            textEditAmount.DataBindings.Add("Text", orderMxs, "Amount");
            calcEditPrice.DataBindings.Add("EditValue", orderMxs, "SPrice");
            checkEditIsCut.DataBindings.Add("EditValue", orderMxs, "IsCut");
        }

        private void BindMX()
        {
            gridControlOrderMX.DataSource = orderMxs;
        }

        private void ChangeEditMode(EditMode editMode)
        {
            switch (editMode)
            {
                case EditMode.Normal:
                    {
                        mode = EditMode.Normal;
                        gridControlOrder.Enabled = true;

                        gridViewOrder.OptionsBehavior.Editable = false;
                        gridViewOrder.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;
                        gridViewOrderMX.OptionsBehavior.Editable = false;
                        gridViewOrderMX.OptionsBehavior.AllowAddRows = DefaultBoolean.False;
                        gridViewOrderMX.OptionsView.NewItemRowPosition = NewItemRowPosition.None;

                        barButtonSave.Enabled = false;
                        barButtonCancel.Enabled = false;
                        barButtonEdit.Enabled = true;
                        barButtonDelete.Enabled = true;
                        barButtonAdd.Enabled = true;

                        textEditTotalAmount.Enabled = false;
                        tbDesc.Enabled = false;
                        tbOrderID.Enabled = false;
                        LookupCustomer.Enabled = false;
                        LookupSale.Enabled = false;
                        lookUpDept.Enabled = false;
                        LookupLevel.Enabled = false;
                        dateApproval.Enabled = false;
                        dateCommit.Enabled = false;
                        dateCreate.Enabled = false;
                        checkEditCommit.Enabled = false;
                        checkEditApproval.Enabled = false;

                        dxValidationProvider1.RemoveControlError(textEditTotalAmount);
                        dxValidationProvider1.RemoveControlError(tbDesc);
                        dxValidationProvider1.RemoveControlError(LookupCustomer);
                        /////////////////
                        simpleButtonInsert.Enabled = false;
                        simpleButtonDelete.Enabled = false;
                        searchLookupEditProduct.Enabled = false;
                        textEditUnit.Enabled = false;
                        textEditQuant.Enabled = false;
                        textEditAmount.Enabled = false;
                        calcEditPrice.Enabled = false;
                        checkEditIsCut.Enabled = false;
                    }
                    break;
                case EditMode.Edit:
                    {
                        mode = EditMode.Edit;
                        gridControlOrder.Enabled = false;

                        gridViewOrder.OptionsBehavior.Editable = false;
                        gridViewOrder.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;
                        gridViewOrderMX.OptionsBehavior.Editable = false;
                        gridViewOrderMX.OptionsBehavior.AllowAddRows = DefaultBoolean.False;
                        gridViewOrderMX.OptionsView.NewItemRowPosition = NewItemRowPosition.None;

                        barButtonSave.Enabled = true;
                        barButtonCancel.Enabled = true;
                        barButtonEdit.Enabled = false;
                        barButtonDelete.Enabled = false;
                        barButtonAdd.Enabled = false;

                        textEditTotalAmount.Enabled = true;
                        tbDesc.Enabled = true;
                        tbOrderID.Enabled = false;
                        LookupCustomer.Enabled = false;
                        LookupSale.Enabled = false;
                        lookUpDept.Enabled = false;
                        LookupLevel.Enabled = false;
                        dateApproval.Enabled = false;
                        dateCommit.Enabled = false;
                        dateCreate.Enabled = false;
                        checkEditCommit.Enabled = false;
                        checkEditApproval.Enabled = false;

                        dxValidationProvider1.Validate();
                        /////////////////
                        //simpleButtonBegin.Enabled = true;
                        //simpleButtonEnd.Enabled = false;
                        //simpleButtonInsert.Enabled = true;
                        //simpleButtonEdit.Enabled = true;
                        //simpleButtonDelete.Enabled = true;
                        searchLookupEditProduct.Enabled = true;
                        //textEditUnit.Enabled = true;
                        //textEditQuant.Enabled = true;
                        //textEditAmount.Enabled = false;
                        //calcEditPrice.Enabled = true;
                        //checkEditIsCut.Enabled = true;

                        ////
                        ChangeMXEditMoce(EditMode.Edit);
                    }
                    break;
                case EditMode.Add:
                    {
                        mode = EditMode.Add;
                        gridControlOrder.Enabled = false;

                        tbCarryingAmount.DataBindings.Clear();
                        textEditTotalAmount.DataBindings.Clear();
                        tbDesc.DataBindings.Clear();
                        tbOrderID.DataBindings.Clear();
                        LookupCustomer.DataBindings.Clear();
                        LookupSale.DataBindings.Clear();
                        lookUpDept.DataBindings.Clear();
                        //LookupLevel.DataBindings.Clear();
                        dateApproval.DataBindings.Clear();
                        dateCommit.DataBindings.Clear();
                        dateCreate.DataBindings.Clear();
                        checkEditCommit.DataBindings.Clear();
                        checkEditApproval.DataBindings.Clear();
                        checkEditCut.DataBindings.Clear();

                        gridViewOrder.OptionsBehavior.Editable = false;
                        gridViewOrder.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;
                        gridViewOrderMX.OptionsBehavior.Editable = false;
                        gridViewOrderMX.OptionsBehavior.AllowAddRows = DefaultBoolean.False;

                        barButtonSave.Enabled = true;
                        barButtonCancel.Enabled = true;
                        barButtonEdit.Enabled = false;
                        barButtonDelete.Enabled = false;
                        barButtonAdd.Enabled = false;

                        textEditTotalAmount.Enabled = true;
                        tbDesc.Enabled = true;
                        tbOrderID.Enabled = false;
                        LookupCustomer.Enabled = true;
                        LookupSale.Enabled = false;
                        lookUpDept.Enabled = false;
                        LookupLevel.Enabled = false;
                        dateApproval.Enabled = false;
                        dateCommit.Enabled = false;
                        dateCreate.Enabled = false;
                        checkEditCommit.Enabled = false;
                        checkEditApproval.Enabled = false;

                        textEditTotalAmount.Text = null;
                        tbCarryingAmount.Text = null;
                        tbDesc.Text = null;
                        //生成ID
                        tbOrderID.Text = System.Guid.NewGuid().ToString();
                        LookupCustomer.EditValue = null;
                        LookupSale.EditValue = GlobalVar.cUser.UserID;
                        lookUpDept.EditValue = GlobalVar.cUser.DeptID;
                        LookupLevel.EditValue = null;
                        dateApproval.EditValue = null;
                        dateCommit.EditValue = null;
                        dateCreate.EditValue = null;
                        checkEditCommit.EditValue = null;
                        checkEditApproval.EditValue = null;
                        checkEditCut.EditValue = null;

                        dxValidationProvider1.Validate();
                        /////////////////
                        //simpleButtonBegin.Enabled = true;
                        //simpleButtonEnd.Enabled = false;
                        //simpleButtonInsert.Enabled = true;
                        //simpleButtonEdit.Enabled = true;
                        //simpleButtonDelete.Enabled = true;
                        searchLookupEditProduct.Enabled = false;
                        //textEditUnit.Enabled = true;
                        //textEditQuant.Enabled = true;
                        //textEditAmount.Enabled = false;
                        //calcEditPrice.Enabled = true;
                        //checkEditIsCut.Enabled = true;

                        ////
                        ChangeMXEditMoce(EditMode.Add);
                    }
                    break;
            }
        }

        private void ChangeMXEditMoce(EditMode editMode)
        {
            switch (editMode)
            {
                case EditMode.Normal:
                    {
                        gridViewOrderMX.OptionsBehavior.Editable = false;
                        gridControlOrderMX.Enabled = true;
                        simpleButtonInsert.Enabled = false;
                        simpleButtonDelete.Enabled = false;
                        searchLookupEditProduct.Enabled = false;
                        textEditUnit.Enabled = false;
                        textEditQuant.Enabled = false;
                        textEditAmount.Enabled = false;
                        calcEditPrice.Enabled = false;
                        checkEditIsCut.Enabled = false;

                        break;
                    }
                case EditMode.Add:
                    {
                        orderMxs.Clear();
                        //gridControlOrderMX.Enabled = false;
                        simpleButtonInsert.Enabled = true;
                        simpleButtonDelete.Enabled = true;
                        searchLookupEditProduct.Enabled = true;
                        textEditUnit.Enabled = true;
                        textEditQuant.Enabled = true;
                        textEditAmount.Enabled = true;
                        calcEditPrice.Enabled = true;
                        checkEditIsCut.Enabled = true;

                        searchLookupEditProduct.DataBindings.Clear();
                        textEditLength.DataBindings.Clear();
                        textEditWidth.DataBindings.Clear();
                        textEditGrammage.DataBindings.Clear();
                        textEditUnit.DataBindings.Clear();
                        textEditQuant.DataBindings.Clear();
                        calcEditPrice.DataBindings.Clear();
                        checkEditIsCut.DataBindings.Clear();
                        textEditAmount.DataBindings.Clear();

                        searchLookupEditProduct.EditValue = null;
                        textEditLength.Text = null;
                        textEditWidth.Text = null;
                        textEditGrammage.Text = null;
                        textEditUnit.Text = null;
                        textEditQuant.Text = null;
                        calcEditPrice.Text = null;
                        checkEditIsCut.EditValue = null;
                        textEditAmount.Text = null;

                        break;
                    }
                case EditMode.Edit:
                    {
                        gridControlOrderMX.Enabled = true;
                        simpleButtonInsert.Enabled = true;
                        simpleButtonDelete.Enabled = true;
                        searchLookupEditProduct.Enabled = true;
                        textEditUnit.Enabled = true;
                        textEditQuant.Enabled = true;
                        textEditAmount.Enabled = true;
                        calcEditPrice.Enabled = true;
                        checkEditIsCut.Enabled = true;

                        searchLookupEditProduct.DataBindings.Clear();
                        textEditLength.DataBindings.Clear();
                        textEditWidth.DataBindings.Clear();
                        textEditGrammage.DataBindings.Clear();
                        textEditUnit.DataBindings.Clear();
                        textEditQuant.DataBindings.Clear();
                        calcEditPrice.DataBindings.Clear();
                        checkEditIsCut.DataBindings.Clear();
                        textEditAmount.DataBindings.Clear();

                        searchLookupEditProduct.EditValue = null;
                        textEditLength.Text = null;
                        textEditWidth.Text = null;
                        textEditGrammage.Text = null;
                        textEditUnit.Text = null;
                        textEditQuant.Text = null;
                        calcEditPrice.Text = null;
                        checkEditIsCut.EditValue = null;
                        textEditAmount.Text = null;

                        break;
                    }
            }
        }

        private void InitValidationRules()
        {
            ConditionValidationRule notEmptyValidationRule = new ConditionValidationRule();
            notEmptyValidationRule.ConditionOperator = ConditionOperator.IsNotBlank;
            notEmptyValidationRule.ErrorText = "值不能为空！";

            dxValidationProvider1.ValidationMode = ValidationMode.Auto;
            dxValidationProvider1.SetValidationRule(LookupCustomer, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(textEditTotalAmount, notEmptyValidationRule);
        }

        private void OrderForm_Load(object sender, EventArgs e)
        {
            InitGrid();
            InitEditZone();
            InitMx();
            ChangeEditMode(EditMode.Normal);
        }

        private void gridViewOrder_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            GridView view = sender as GridView;
            DataRow row = gridViewOrderMX.GetDataRow(e.RowHandle);

            //view.SetRowCellValue(e.RowHandle, view.Columns["Amount"], "1111");

            this.gridViewOrderMX.UpdateCurrentRow();

            //DataRow row = gridViewOrder.GetDataRow(e.RowHandle);
            //gridViewOrder.AddNewRow();
        }

        /// <summary>
        /// 选择客户后，显示客户级别时允许增行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LookupLevel_EditValueChanged(object sender, EventArgs e)
        {
            if (LookupLevel.EditValue != null && (mode.Equals(EditMode.Edit) || mode.Equals(EditMode.Add)))
            {
                //gridViewOrderMX.OptionsBehavior.Editable = true;
                //gridViewOrderMX.OptionsBehavior.AllowAddRows = DefaultBoolean.True;
                //gridViewOrderMX.OptionsView.NewItemRowPosition = NewItemRowPosition.Top;
                //simpleButtonInsert.Enabled = true;
                ChangeMXEditMoce(EditMode.Add);
                //searchLookupEditProduct.Enabled = true;
            }
        }

        private static object GetLevel(string customerid)
        {
            IQueryable<TbCustomer> customers = from i in GlobalVar.GCustomers
                                               where i.CustomerID == customerid
                                               select i;
            if (customers.Any())
            {
                return customers.FirstOrDefault().Level;
            }
            else
            {
                return null;
            }

        }

        private double QueryPrice(string product, int level)
        {
            var dbConText = new JYEntities();
            IQueryable<TbPrice> price = from p in GlobalVar.GPrices
                                        where p.ProductID == product && p.Level == level
                                        select p;
            if (price.Any())
            {
                return price.FirstOrDefault().Price.Value;
            }
            else
            {
                MessageBox.Show("该商品价格定义有误，请检查！");
                return 100000000.0;
            }
        }

        private void gridViewOrder_InvalidRowException(object sender, InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = ExceptionMode.NoAction;
        }

        private void LookupCustomer_EditValueChanged(object sender, EventArgs e)
        {
            if (!(LookupCustomer.EditValue == null))
            {
                LookupLevel.EditValue = Convert.ToInt64(GetLevel(LookupCustomer.EditValue.ToString()));
            }
        }

        private void barButtonAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ChangeEditMode(EditMode.Add);
        }

        private void barButtonEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (checkEditApproval.Checked || checkEditCommit.Checked)
            {
                MessageBox.Show("单据已提交，不允许修改！");
                return;
            }
            ChangeEditMode(EditMode.Edit);
        }

        private void barButtonSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var dbContext = new JYEntities();
            if (orderMxs.Count > 0)
            {
                switch (mode)
                {
                    case EditMode.Normal:
                        break;
                    case EditMode.Add:
                        {
                            TbOrder neworder= new TbOrder();

                            neworder.OrderID = tbOrderID.Text;
                            neworder.CustomerID = LookupCustomer.EditValue.ToString();
                            neworder.CREATEBY = GlobalVar.cUser.UserID;
                            neworder.DeptID = int.Parse(lookUpDept.EditValue.ToString());
                            neworder.ODesc = tbDesc.Text;
                            neworder.CarryingAmount = double.Parse(tbCarryingAmount.Text);
                            neworder.Amount = textEditTotalAmount.Text == "" ? double.Parse(tbCarryingAmount.Text) : double.Parse(textEditTotalAmount.Text);

                            dbContext.Add(neworder);
                            dbContext.SaveChanges();
                            foreach (TbOrderMX mx in orderMxs)
                            {
                                TbOrderMX orderMx = new TbOrderMX();

                                    orderMx.Amount = mx.Amount;
                                    orderMx.IsCut = mx.IsCut;
                                    orderMx.OrderID = mx.OrderID;
                                    orderMx.Plength = mx.Plength;
                                    orderMx.ProductID = mx.ProductID;
                                    orderMx.Pweight = mx.Pweight;
                                    orderMx.Pwidth = mx.Pwidth;
                                    orderMx.Quant = mx.Quant;
                                    orderMx.SPrice = mx.SPrice;
                                    orderMx.Unit = mx.Unit;

                                    dbContext.Add(mx);
                                    dbContext.SaveChanges();
                            }

                            InitGrid();
                            InitEditZone();
                            InitMx();
                           
                            break;
                        }
                    case EditMode.Edit:
                        {
                            TbOrder orderEdit =
                                dbContext.TbOrders.Where(o => o.OrderID == tbOrderID.Text).FirstOrDefault();
                            orderEdit.CarryingAmount = double.Parse(tbCarryingAmount.Text);
                            orderEdit.Amount = textEditTotalAmount.Text == "" ? double.Parse(tbCarryingAmount.Text) : double.Parse(textEditTotalAmount.Text);
                            orderEdit.ODesc = tbDesc.Text;
                            dbContext.SaveChanges();

                            ///执行删除明细
                            foreach (TbOrderMX dMx in orderMxsImage)
                            {
                                var d = from i in orderMxs
                                        where i.ID == dMx.ID
                                        select i;

                                if (d.Any())
                                {
                                    ;
                                }
                                else
                                {
                                    dbContext.Delete(dbContext.TbOrderMXes.Where(o=>o.ID==dMx.ID));
                                }

                            }

                            foreach (TbOrderMX mx in orderMxs)
                            {
                                if (mx.ID == 0)
                                {
                                    TbOrderMX orderMx = new TbOrderMX();

                                    orderMx.Amount = mx.Amount;
                                    orderMx.IsCut = mx.IsCut;
                                    orderMx.OrderID = mx.OrderID;
                                    orderMx.Plength = mx.Plength;
                                    orderMx.ProductID = mx.ProductID;
                                    orderMx.Pweight = mx.Pweight;
                                    orderMx.Pwidth = mx.Pwidth;
                                    orderMx.Quant = mx.Quant;
                                    orderMx.SPrice = mx.SPrice;
                                    orderMx.Unit = mx.Unit;

                                    dbContext.Add(mx);
                                    dbContext.SaveChanges();
                                }
                                else
                                {
                                    TbOrderMX mxEdit = dbContext.TbOrderMXes.Where(o => o.ID == mx.ID).FirstOrDefault();

                                    mxEdit.Amount = mx.Amount;
                                    mxEdit.IsCut = mx.IsCut;
                                    mxEdit.OrderID = mx.OrderID;
                                    mxEdit.Plength = mx.Plength;
                                    mxEdit.ProductID = mx.ProductID;
                                    mxEdit.Pweight = mx.Pweight;
                                    mxEdit.Pwidth = mx.Pwidth;
                                    mxEdit.Quant = mx.Quant;
                                    mxEdit.SPrice = mx.SPrice;
                                    mxEdit.Unit = mx.Unit;

                                    dbContext.SaveChanges();
                                }

                            }
                            InitGrid();
                            InitEditZone();
                            InitMx();
                           
                            break;
                        }
                }

            }
            else //根据初始保存值检查，如果初始是有值的，则删除原来所有对象
            {
                if (orderMxsImage.Count > 0)
                {
                    foreach (TbOrderMX mx in orderMxsImage)
                    {
                       dbContext.Delete(mx); 
                    }
                    dbContext.SaveChanges();
                }
                TbOrder orderEdit =
                    dbContext.TbOrders.Where(o => o.OrderID == tbOrderID.Text).FirstOrDefault();
                orderEdit.Amount = 0;
                //dbContext.Delete(dbContext.TbOrderMXes.Where(o=>o.OrderID==tbOrderID.Text));
                dbContext.SaveChanges();
            }


            ChangeEditMode(EditMode.Normal);
        }

        private void barButtonCancel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            orderMxs.Clear();
            if (orderMxsImage.Count > 0)
            {
                foreach (TbOrderMX mx in orderMxsImage)
                {
                    orderMxs.Add(mx);
                }
            }
            ChangeEditMode(EditMode.Normal);
            InitEditZone();
        }

        private void barButtonDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (string.IsNullOrEmpty(tbOrderID.Text))
            {
                MessageBox.Show("该单据不存在!");
                return;
            }
            else
            {
                var dbContext = new JYEntities();
                IQueryable<TbOrder> orders = from i in dbContext.TbOrders
                                             where
                                                 i.OrderID == tbOrderID.Text &&
                                                 i.IsCommit != true &&
                                                 i.IsApproval != true &&
                                                 i.CREATEBY == GlobalVar.cUser.UserID
                                             select i;
                if (orders.Any())
                {
                    IQueryable<TbOrderMX> ordermxs = from i in dbContext.TbOrderMXes
                                                     where
                                                         i.OrderID == tbOrderID.Text
                                                     select i;
                    if (orders.Any())
                    {
                        dbContext.Delete(ordermxs);
                    }
                    dbContext.Delete(orders);
                    dbContext.SaveChanges();
                }
                else
                {
                    MessageBox.Show(@"提示：单据不存在或无权限！仅能删除本人创建且未提交的订单。");
                }

            }
            ChangeEditMode(EditMode.Normal);
            InitGrid();
        }

        private void barButtonCommit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (CheckRight.Check(GlobalVar.cUser.UserID, 3, GlobalVar.RightType.Commit))
            {
                if (string.IsNullOrEmpty(tbOrderID.Text))
                {
                    MessageBox.Show("该单据不存在!");
                    return;
                }
                else
                {
                    var dbContext = new JYEntities();
                    IQueryable<TbOrder> orders = from i in dbContext.TbOrders
                                                 where
                                                     i.OrderID == tbOrderID.Text &&
                                                     i.IsCommit != true &&
                                                     i.IsApproval != true &&
                                                     i.CREATEBY == GlobalVar.cUser.UserID
                                                 select i;
                    if (orders.Any())
                    {
                        orders.FirstOrDefault().IsCommit = true;
                        orders.FirstOrDefault().CommitDate = DateTime.Now;

                        dbContext.SaveChanges();
                    }
                    else
                    {
                        MessageBox.Show(@"提示：单据已提交或已审批！");
                    }

                }
                ChangeEditMode(EditMode.Normal);
                InitGrid();
            }
            else
            {
                MessageBox.Show(@"您无此权限!");
            }

        }

        private void barButtonApproval_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (CheckRight.Check(GlobalVar.cUser.UserID, 3, GlobalVar.RightType.Approval))
            {
                if (string.IsNullOrEmpty(tbOrderID.Text))
                {
                    MessageBox.Show("该单据不存在!");
                    return;
                }
                else
                {
                    var dbContext = new JYEntities();
                    IQueryable<TbOrder> orders = from i in dbContext.TbOrders
                                                 where
                                                     i.OrderID == tbOrderID.Text &&
                                                     i.IsCommit == true &&
                                                     i.IsApproval != true
                                                 select i;
                    if (orders.Any())
                    {
                        orders.FirstOrDefault().IsApproval = true;
                        orders.FirstOrDefault().ApprovalDate = DateTime.Now;

                        dbContext.SaveChanges();
                    }
                    else
                    {
                        MessageBox.Show(@"提示：单据已审批或尚未提交！");
                    }

                }
                ChangeEditMode(EditMode.Normal);
                InitGrid();
            }
            else
            {
                MessageBox.Show(@"您无此权限!");
            }
            
        }

        private void barButtonItemReject_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (CheckRight.Check(GlobalVar.cUser.UserID, 3, GlobalVar.RightType.Reject))
            {
                if (string.IsNullOrEmpty(tbOrderID.Text))
                {
                    MessageBox.Show("该单据不存在!");
                    return;
                }
                else
                {
                    var dbContext = new JYEntities();
                    IQueryable<TbOrder> orders = from i in dbContext.TbOrders
                                                 where
                                                     i.OrderID == tbOrderID.Text &&
                                                     i.IsCommit == true &&
                                                     i.IsApproval != true
                                                 select i;
                    if (orders.Any())
                    {
                        orders.FirstOrDefault().IsCommit = false;

                        dbContext.SaveChanges();
                    }
                    else
                    {
                        MessageBox.Show(@"提示：单据未提交或已审批！");
                    }

                }
                ChangeEditMode(EditMode.Normal);
                InitGrid();
            }
            else
            {
                MessageBox.Show(@"您无此权限!");
            }
            
        }

        private void barButtonSearch_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridViewOrder.FindPanelVisible = true;
        }

        private void gridViewOrder_RowClick(object sender, RowClickEventArgs e)
        {
            //gridViewOrder.CancelSelection();
            //int selectedHandle = gridViewOrder.GetSelectedRows()[0];
            //string orderID = gridViewOrder.GetRowCellValue(selectedHandle, "OrderID").ToString();
            //
            //gridControlOrderMX.DataSource = null;
            //
            //var dbContext = new JYEntities();
            //IQueryable<TbOrderMX> mxs = from i in dbContext.TbOrderMXes
            //                            where i.OrderID == orderID
            //                            select i;
            //if (mxs.Any())
            //{
            //    orderMXBinding.DataSource = mxs;
            //    gridControlOrderMX.DataSource = orderMXBinding;
            //}
            //else
            //{
            //    orderMXBinding.DataSource = tbOrderMxs;
            //    gridControlOrderMX.DataSource = orderMXBinding;
            //}
            InitMx();
            InitMxEdit();
        }

        private void gridViewOrder_ValidateRow(object sender, ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;
            GridColumn productColumn = view.Columns["ProductID"];
            GridColumn lengthColumn = view.Columns["Plength"];
            GridColumn widthColumn = view.Columns["Pwidth"];
            GridColumn priceColumn = view.Columns["SPrice"];
            GridColumn amountColumn = view.Columns["Amount"];

            string productid = view.GetRowCellValue(e.RowHandle, productColumn).ToString();

            var dbContext = new JYEntities();
            IQueryable<TbProduct> products = from i in GlobalVar.GProductsAll
                                             where i.ProductID == productid
                                             select i;



            //if (view.GetRowCellValue(e.RowHandle, length)==null || view.GetRowCellValue(e.RowHandle, length).Equals(DBNull.Value))
            //{
            //    e.Valid = false;
            //    view.SetColumnError(length, "长度不能为空！");
            //}
            //if (view.GetRowCellValue(e.RowHandle, width) == null || view.GetRowCellValue(e.RowHandle, width).Equals(DBNull.Value))
            //{
            //    e.Valid = false;
            //    view.SetColumnError(width, "宽度不能为空！");
            //}
            if (view.GetRowCellValue(e.RowHandle, priceColumn) == null || view.GetRowCellValue(e.RowHandle, priceColumn).Equals(DBNull.Value))
            {
                e.Valid = false;
                view.SetColumnError(priceColumn, "价格不能为空！");
            }


            double? length;
            double? width;
            double? price;
            double? grammage;

            if (products.Any())
            {
                TbProduct p = products.FirstOrDefault();
                length = p.Lengths;
                width = p.Widths;
                price = double.Parse(view.GetRowCellValue(e.RowHandle, priceColumn).ToString());
                grammage = p.Grammage;

                if (price * 1000000.0 / (length * 0.001 * width * .001 * grammage) < QueryPrice(productid, int.Parse(LookupLevel.EditValue.ToString())))
                {
                    e.Valid = false;
                    view.SetColumnError(priceColumn, "单价不能低于定价水平！");
                }
            }

            //  SELECT 26250*0.8*0.8*100/1000000.0
            //  SELECT 12*1000000/(0.8*0.8*100)
            //  单价*1000000/(长*宽*克重)<吨价


        }

        private void gridViewOrderMX_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            DataRow row = gridViewOrderMX.GetDataRow(e.RowHandle);
            int intRowHandle = e.RowHandle;

            string a = Convert.ToString(gridViewOrderMX.GetRowCellValue(intRowHandle, "IsCut"));

            if (row != null && row["SPrice"] != DBNull.Value && row["Quant"] != DBNull.Value)
            {
                if (row["IsCut"].ToString() == "True")
                    row["Amount"] = float.Parse(row["SPrice"].ToString()) * int.Parse(row["Quant"].ToString()) * 1.05;
                row["Amount"] = float.Parse(row["SPrice"].ToString()) * int.Parse(row["Quant"].ToString());
            }
        }


        //  private void gridView1_CellValueChanged(object sender, CellValueChangedEventArgs e)
        //      {
        //          DataRow row = gridViewOrder.GetDataRow(e.RowHandle);
        //      DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
        //
        //      if (row != null && row["Plength"] != DBNull.Value && row["Pwidth"] != DBNull.Value && row["sPrice"] != DBNull.Value && row["Quant"] != DBNull.Value)
        //      {
        //          row["Amount"] = float.Parse(row["sPrice"].ToString()) * int.Parse(row["Quant"].ToString());
        //          //row["ProductID"] = row["kindid"].ToString()
        //          //    + "-" + row["color"].ToString()
        //          //    + "-" + row["grammage"].ToString()
        //          //    + "-" + row["texture"].ToString()
        //          //    + "-" + row["padding"].ToString()
        //          //    + "-" + row["Process"].ToString();
        //
        //          //row["ProductName"] = gridView1.GetRowCellDisplayText(e.RowHandle, view.Columns["kindid"]).ToString()
        //          //    + "-" + gridView1.GetRowCellDisplayText(e.RowHandle, view.Columns["color"]).ToString()
        //          //    + "-" + gridView1.GetRowCellDisplayText(e.RowHandle, view.Columns["grammage"]).ToString()
        //          //    + "-" + gridView1.GetRowCellDisplayText(e.RowHandle, view.Columns["texture"]).ToString()
        //          //    + "-" + gridView1.GetRowCellDisplayText(e.RowHandle, view.Columns["padding"]).ToString()
        //          //    + "-" + gridView1.GetRowCellDisplayText(e.RowHandle, view.Columns["Process"]).ToString();
        //      }
        //  }

        /// <summary>
        /// 明细表行点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridViewOrderMX_RowClick(object sender, RowClickEventArgs e)
        {

        }

        /// <summary>
        /// 价格检查
        /// </summary>
        /// <returns>2：产品、数量、单价为空；1：低于定价；0：正常</returns>
        private int CheckPrice()
        {
            if (searchLookupEditProduct.EditValue == null || string.IsNullOrEmpty(textEditLength.Text)
                || string.IsNullOrEmpty(textEditWidth.Text) || string.IsNullOrEmpty(textEditGrammage.Text)
                || string.IsNullOrEmpty(textEditQuant.Text) || string.IsNullOrEmpty(textEditAmount.Text))
            {
                return 2;
            }
            else
            {
                double DPrice = QueryPrice(searchLookupEditProduct.EditValue.ToString(), int.Parse(LookupLevel.EditValue.ToString()));
                double SPrice = double.Parse(calcEditPrice.EditValue.ToString()) * 1000000.0 / (double.Parse(textEditLength.Text) * 0.001 * double.Parse(textEditWidth.Text) * .001 * double.Parse(textEditGrammage.Text));
                if (DPrice > SPrice)
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
        }

        private double CalcAmount()
        {
            if (string.IsNullOrEmpty(calcEditPrice.Text) || textEditQuant.EditValue == null)
            {
                return 0;
            }
            else
            {
                double amount = double.Parse(calcEditPrice.EditValue.ToString()) * double.Parse(textEditQuant.Text);
                if (checkEditIsCut.Checked)
                {
                    return amount * 1.05;
                }
                else
                {
                    return amount;
                }
            }
        }

        private void searchLookupEditProduct_EditValueChanged(object sender, EventArgs e)
        {
            if (!(searchLookupEditProduct.EditValue == null))
            {
                var dbContext = new JYEntities();
                IQueryable<TbProduct> products = from i in GlobalVar.GProductsAll
                                                 where i.ProductID == searchLookupEditProduct.EditValue
                                                 select i;
                if (products.Any())
                {
                    textEditLength.Text = products.FirstOrDefault().Lengths.ToString();
                    textEditWidth.Text = products.FirstOrDefault().Widths.ToString();
                    textEditGrammage.Text = products.FirstOrDefault().Grammage.ToString();
                }
            }
        }

        private void textEditQuant_EditValueChanged(object sender, EventArgs e)
        {
            textEditAmount.EditValue = CalcAmount();
        }

        private void calcEditPrice_EditValueChanged(object sender, EventArgs e)
        {
            textEditAmount.EditValue = CalcAmount();
        }

        private void checkEditIsCut_CheckStateChanged(object sender, EventArgs e)
        {
            textEditAmount.EditValue = CalcAmount();
        }

        private void simpleButtonInsert_Click(object sender, EventArgs e)
        {
            if (LookupCustomer.EditValue == null || LookupLevel.EditValue == null)
            {
                MessageBox.Show(@"客户、客户级别不能为空！");
            }
            else
            {
                switch (CheckPrice())
                {
                    case 2:
                        {
                            MessageBox.Show(@"产品、数量、单价不能为空！");
                            break;
                        }
                    case 1:
                        {
                            MessageBox.Show(@"不能低于定价！");
                            break;
                        }
                    case 0:
                        {
                            TbOrderMX mx = new TbOrderMX();
                            mx.OrderID = tbOrderID.Text;
                            mx.ProductID = searchLookupEditProduct.EditValue.ToString();
                            mx.Plength = double.Parse(textEditLength.Text);
                            mx.Pwidth = double.Parse(textEditWidth.Text);
                            mx.Pweight = double.Parse(textEditGrammage.Text);
                            mx.Unit = string.IsNullOrEmpty(textEditUnit.Text) ? 0 : int.Parse(textEditUnit.Text);
                            mx.Quant = int.Parse(textEditQuant.Text);
                            mx.SPrice = double.Parse(calcEditPrice.EditValue.ToString());
                            mx.IsCut = checkEditIsCut.Checked;
                            mx.Amount = double.Parse(textEditAmount.Text);

                            orderMxs.Add(mx);

                            tbCarryingAmount.Text = orderMxs.Sum(o => o.Amount).ToString();
                            textEditTotalAmount.Text = orderMxs.Sum(o => o.Amount).ToString();
                            //////////////// 插入后清空编辑区
                            searchLookupEditProduct.EditValue = null;
                            textEditLength.Text = null;
                            textEditWidth.Text = null;
                            textEditGrammage.Text = null;
                            textEditUnit.Text = null;
                            textEditQuant.Text = null;
                            calcEditPrice.Text = null;
                            checkEditIsCut.EditValue = null;
                            textEditAmount.Text = null;
                            break;
                        }
                }
                BindMX();
            }
        }

        private void simpleButtonDelete_Click(object sender, EventArgs e)
        {
            gridViewOrderMX.DeleteSelectedRows();
            if (orderMxs.Any())
            {
                tbCarryingAmount.Text = orderMxs.Sum(o => o.Amount).ToString();
                textEditTotalAmount.Text = orderMxs.Sum(o => o.Amount).ToString();
            }
        }

        #region 查看全部订单
        #endregion
        /**
         * 全部订单
         */
        private void radioButtonAll_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonAll.Checked)
            {
                var dbContext = new JYEntities();
                var orders = from i in dbContext.TbOrders
                             from c in GlobalVar.GCustomers
                             where i.CustomerID == c.CustomerID
                             orderby i.CreateDate descending
                             select new { i.CarryingAmount, i.Amount, i.CREATEBY, i.CreateDate, i.CustomerID, i.Cut, i.DeptID, i.IsApproval, i.IsCommit, i.IsDeleted, i.LastEditDate, i.ODesc, i.OrderID, i.CommitDate, i.ApprovalDate, c.Level };
                if (orders.Any())
                {
                    orderBinding.DataSource = orders; //订单
                    BindData();
                    InitMx();
                }
                else
                {
                    //MessageBox.Show(@"无订单！");
                    orderBinding.Clear();
                    orderMxs.Clear();
                }
            }
        }


        /**
         * 待办订单
         */
        private void radioButtonTask_CheckedChanged(object sender, EventArgs e)
        {
            orderBinding.Clear();
            if (radioButtonTask.Checked)
            {
                var dbContext = new JYEntities();
                var orders = from i in dbContext.TbOrders
                             from c in GlobalVar.GCustomers
                             where i.CustomerID == c.CustomerID && i.IsCommit != true && i.IsApproval != true
                             orderby i.CreateDate descending
                             select new { i.CarryingAmount, i.Amount, i.CREATEBY, i.CreateDate, i.CustomerID, i.Cut, i.DeptID, i.IsApproval, i.IsCommit, i.IsDeleted, i.LastEditDate, i.ODesc, i.OrderID, i.CommitDate, i.ApprovalDate, c.Level };
                if (orders.Any())
                {
                    orderBinding.DataSource = orders; //订单
                    BindData();
                    InitMx();
                }
                else
                {
                    //MessageBox.Show(@"无未提交订单！");
                    orderBinding.Clear();
                    orderMxs.Clear();
                }
            }
        }

        /**
         * 已办
         */
        private void radioButtonFinish_CheckedChanged(object sender, EventArgs e)
        {
            orderBinding.Clear();
            if (radioButtonFinish.Checked)
            {
                var dbContext = new JYEntities();
                var orders = from i in dbContext.TbOrders
                             from c in GlobalVar.GCustomers
                             where i.CustomerID == c.CustomerID && i.IsCommit == true
                             orderby i.CreateDate descending
                             select new { i.CarryingAmount, i.Amount, i.CREATEBY, i.CreateDate, i.CustomerID, i.Cut, i.DeptID, i.IsApproval, i.IsCommit, i.IsDeleted, i.LastEditDate, i.ODesc, i.OrderID, i.CommitDate, i.ApprovalDate, c.Level };
                if (orders.Any())
                {
                    orderBinding.DataSource = orders; //订单
                    BindData();
                    InitMx();
                }
                else
                {
                    MessageBox.Show(@"无已提交订单！");
                    radioButtonAll.Checked = true;
                }
            }
        }

        /**
         * 办结
         */
        private void radioButtonProcess_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonProcess.Checked)
            {
                var dbContext = new JYEntities();
                var orders = from i in dbContext.TbOrders
                             from c in GlobalVar.GCustomers
                             where i.CustomerID == c.CustomerID && i.IsApproval == true
                             orderby i.CreateDate descending
                             select new { i.CarryingAmount, i.Amount, i.CREATEBY, i.CreateDate, i.CustomerID, i.Cut, i.DeptID, i.IsApproval, i.IsCommit, i.IsDeleted, i.LastEditDate, i.ODesc, i.OrderID, i.CommitDate, i.ApprovalDate, c.Level };
                if (orders.Any())
                {
                    orderBinding.DataSource = orders; //订单
                    BindData();
                    InitMx();
                }
                else
                {
                    //MessageBox.Show(@"无已审核订单！");
                    orderBinding.Clear();
                    orderMxs.Clear();
                }
            }
        }

    }

    public class MyOrder
    {
        public double? CarryingAmount { get; set; }
        public double? Amount { get; set; }
        public long? CREATEBY { get; set; }
        public DateTime? CreateDate { get; set; }
        public string CustomerID {get;set;}
        public bool? Cut { get; set; }
        public int? DeptID { get; set; }
        public bool? IsApproval { get; set; }
        public bool? IsCommit { get; set; }
        public bool? IsDeleted { get; set; }
        public DateTime? LastEditDate { get; set; }
        public string ODesc { get; set; }
        public string OrderID { get; set; }
        public DateTime? CommitDate { get; set; }
        public DateTime? ApprovalDate { get; set; }
        public int? Level { get; set; }
    }
}
